// upload.go
package controllers_common

import (
	"io"
	"log"
	"martini_template/componnet"
	"martini_template/form"
	"net/http"
	"os"
	"path/filepath"
	"syscall"
	"time"

	"github.com/Unknwon/goconfig"
	"github.com/martini-contrib/render"
	"github.com/satori/go.uuid"
)

//初始化上传目录
var fileSaveDirectory = "static/uploads"
var folder string

func init() {
	mask := syscall.Umask(0)
	defer syscall.Umask(mask)
	folder = componnet.Md5String(time.Now().Month().String())
	fileSaveDirectory = fileSaveDirectory + "/" + folder + "/"
	absUploadDir, err := filepath.Abs(fileSaveDirectory)
	if err != nil {
		componnet.Elogger.Println(err)
	} else {
		_, ferr := os.Stat(absUploadDir)
		if ferr != nil {
			merr := os.MkdirAll(absUploadDir, os.ModeDir)
			if merr != nil {
				componnet.Elogger.Println(merr)
			}
		}
	}
}

type Upload struct {
}

func (c Upload) UploadFile(resJson componnet.ResponsJson, appEnv string, req *http.Request, appConfig *goconfig.ConfigFile, uploadForm form.UploadForm, r render.Render, flogger *log.Logger) {
	flogger.Println(uploadForm)
	if uploadForm.UpFile == nil {
		resJson.SetState(componnet.CODE_UPLOAD_FILE_MISS)
		r.JSON(200, resJson)
		return
	}
	fhandle, ferr := uploadForm.UpFile.Open()
	if ferr != nil {
		componnet.Elogger.Println(ferr)
	}
	defer fhandle.Close()
	newFilename := makeNewFilename(filepath.Ext(uploadForm.UpFile.Filename))
	newFilePath, nerr := filepath.Abs(fileSaveDirectory + "/" + newFilename)
	if nerr != nil {
		componnet.Elogger.Println(nerr)
	}
	newFile, ferr := os.Create(newFilePath)
	if ferr != nil {
		componnet.Elogger.Println(ferr)
	}
	writeByte, werr := io.Copy(newFile, fhandle)
	newFile.Close()
	if werr != nil {
		componnet.Elogger.Println(werr)
		resJson.SetState(componnet.CODE_UPLOAD_FILE_FILE_ERR)
		r.JSON(200, resJson)
		return
	}
	if writeByte == 0 {
		resJson.SetState(componnet.CODE_UPLOAD_FILE_FILE_ERR)
		r.JSON(200, resJson)
		return
	}
	//判断文件大小
	maxFileSize := appConfig.MustInt64(appEnv, "upload_max_size", 10000)
	fileInfo, ierr := os.Stat(newFilePath)
	if ierr != nil {
		componnet.Elogger.Println(ierr)
	}
	if (fileInfo.Size() / 1024) > maxFileSize {
		rerr := os.Remove(newFilePath)
		if rerr != nil {
			componnet.Elogger.Println(rerr)
		}
		resJson.SetState(componnet.CODE_UPLOAD_SIZE_ERR)
		r.JSON(200, resJson)
		return
	}
	resJson.SetState(componnet.CODE_SUCC)
	resData := make(map[string]string)
	//resData["AbsPath"] = getAbsPath(newFilePath)
	staticDirectory, _ := appConfig.GetValue(appEnv, "static_directory")
	resData["RePath"] = getRePath(staticDirectory, newFilePath)
	domain, _ := appConfig.GetValue(appEnv, "domain")
	resData["AbsPath"] = componnet.ImageUrlPath(domain, resData["RePath"])
	resJson.SetDataStruct(resData)
	r.JSON(200, resJson)
	return
}

func makeNewFilename(ext string) string {
	newName := uuid.NewV1().String() + ext
	return newName
}

//func getAbsPath(base string, path string) string {

//}

func getRePath(base string, path string) string {
	repath := "uploads" + string(filepath.Separator) + folder + string(filepath.Separator) + filepath.Base(path)
	return repath
}
